<?php defined('_JEXEC') or die('Restricted access');
/**
 * @package             Joomla
 * @subpackage          CeltaWeb Traffic Component
 * @author              Steven Palmer
 * @author url          http://coalaweb.com
 * @author email        support@coalaweb.com
 * @license             GNU/GPL, see /files/en-GB.license.txt
 * @copyright           Copyright (c) 2012 Steven Palmer All rights reserved.
 * @version             Version 0.0.7 September 2012
 * 
 * The CeltaWeb traffic module was inspired by VCNT Thanks to Viktor Vogel {@link http://joomla-extensions.kubik-rubik.de/}
 * 
 * CeltaWeb Traffic is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class mod_celtawebtrafficHelper extends JObject
{
	protected $db;
        
        /**
         * Constructor
         *
         * @access private
         * Set the databse object
         *
         */
	function __construct() 
	{
		$this->set('db', JFactory::getDbo());
	}

	// Function - set call
	function count(&$params)
	{
		$locktime 	=	$params->get('locktime', 60);
		$nobots		=	$params->get('nobots');
		$botslist	=	$params->get('botslist');
		$noip 		= 	$params->get('noip');
		$ipslist	= 	$params->get('ipslist');		
		$locktime	=	$locktime * 60;
                $time_offset    =       $params->get('timeoffset',0);
		$now		=	time()+ $time_offset;
		$ip		=	$_SERVER['REMOTE_ADDR'];
		
		// Keep out bots
		$bot = 0;
		if ($nobots) 
		{
			if (isset($_SERVER['HTTP_USER_AGENT'])) 
			{
				$agent = $_SERVER['HTTP_USER_AGENT'];
				$bots_array =  explode(",", $botslist);
				foreach ( $bots_array as $e ) 
				{
					if (preg_match('/'.trim($e).'/i', $agent)) 
					{
						$bot = 1;
					}
				}
			} 
			else // Do not count if no user agent is transmitted
			{ 
				$bot = 1;
			}
		}
		
		// Lock out IP addresses
		$iplock = 0;
		if ($noip) 
		{
			if (isset($_SERVER['REMOTE_ADDR'])) 
			{
				$agent = $_SERVER['REMOTE_ADDR'];
				$bots_array = explode(",", $ipslist);
				foreach ($bots_array as $e) 
				{	
					if (preg_match('/'.trim($e).'/i', $agent)) 
					{
						$iplock = 1;
					}
				}
			} 
			else // Do not lock if no IP is provided
			{ 
				$iplock = 1;
			}
		}
		
		
		// Check if IP already exists and reload lock expired
		$query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic')." where ".$this->db->nameQuote('ip')." = ".$this->db->quote($ip)." and (".$this->db->nameQuote('tm')." + ".$this->db->quote($locktime).") > ".$this->db->quote($now);
		$this->db->setQuery($query);
		$result = $this->db->query();
                $items = $this->db->loadResult();
		
		// Call count, if conditions are met
		if (empty($items) AND ($bot == 0) AND ($iplock == 0)) 
		{
			$query = "insert into ".$this->db->nameQuote('#__cwtraffic')." (".$this->db->nameQuote('tm').", ".$this->db->nameQuote('ip').") values (".$this->db->quote($now).", ".$this->db->quote($ip).")";
			$this->db->setQuery($query);
			$result = $this->db->query();
			$e = $this->db->getErrorMsg();
		}
		return;
	}
	
	// Function - Reading Views
	function read(&$params)
	{
		// Times are calculated
		$date = JFactory::getDate();
		$date->setOffset(JFactory::getApplication()->getCfg('offset'));
		
		$day 			=	$date->toFormat('%d');
		$month			=	$date->toFormat('%m');
		$year			=	$date->toFormat('%Y');
		$daystart		=	mktime(0,0,0,$month,$day,$year);
		$monthstart		=	mktime(0,0,0,$month,1,$year);
		$weekday		=	$date->toFormat('%w');
		$weekday--;
		if ($weekday < 0) { $weekday = 7; }
		$weekday		=	$weekday * 24*60*60;
		$weekstart		=	$daystart - $weekday;
		$yesterdaystart         =	$daystart - (24*60*60);
		$preset			= 	$params->get('preset', 0);
                
                //Read ongoing total after cleanup
                $query = "SELECT TCOUNT FROM ".$this->db->nameQuote('#__cwtraffic_total');
                $this->db->setQuery($query);
                $tcount = $this->db->loadResult();
        
		// Values ​​read
		$query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic');
		$this->db->setQuery($query);
		$result = $this->db->query();
		$all_visitors = $this->db->loadResult();
		$all_visitors += $preset;
                $all_visitors += $tcount;

		$query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic')." where ".$this->db->nameQuote('tm').">".$this->db->quote($daystart);
		$this->db->setQuery($query);
		$result = $this->db->query();
		$today_visitors = $this->db->loadResult();

		$query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic')." where ".$this->db->nameQuote('tm').">".$this->db->quote($yesterdaystart)." and ".$this->db->nameQuote('tm')."<".$this->db->quote($daystart);
		$this->db->setQuery($query);
		$result = $this->db->query();
		$yesterday_visitors = $this->db->loadResult();

		$query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic')." where ".$this->db->nameQuote('tm').">=".$this->db->quote($weekstart);
		$this->db->setQuery($query);
		$result = $this->db->query();
		$week_visitors = $this->db->loadResult();

		$query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic')." where ".$this->db->nameQuote('tm').">=".$this->db->quote($monthstart);
		$this->db->setQuery($query);
		$result = $this->db->query();
		$month_visitors = $this->db->loadResult();

		$ret = array($all_visitors, $today_visitors, $yesterday_visitors, $week_visitors, $month_visitors);
		return ($ret);
	}
	
            /**
            * Returns an array containing web visitor information
            *
            * @access public
            * @static
            * @return array
            *
            */
            
           public static function getBrowser()
            {
                $u_agent = $_SERVER['HTTP_USER_AGENT'];
                $bname = 'Unknown';
                $platform = 'Unknown';

                //First get the platform?
                if (preg_match('/linux/i', $u_agent)) {
                    $platform = 'Linux';
                }
                elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
                    $platform = 'Mac';
                }
                elseif (preg_match('/windows|win32/i', $u_agent)) {
                    $platform = 'Windows';
                }

                // Next get the name of the useragent yes seperately and for good reason
                if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
                {
                    $bname = 'IE';
                    $ub = "MSIE";
                }
                elseif(preg_match('/Firefox/i',$u_agent))
                {
                    $bname = 'Firefox';
                    $ub = "Firefox";
                }
                elseif(preg_match('/Chrome/i',$u_agent))
                {
                    $bname = 'Chrome';
                    $ub = "Chrome";
                }
                elseif(preg_match('/Safari/i',$u_agent))
                {
                    $bname = 'Safari';
                    $ub = "Safari";
                }
                elseif(preg_match('/Opera/i',$u_agent))
                {
                    $bname = 'Opera';
                    $ub = "Opera";
                }
                elseif(preg_match('/Netscape/i',$u_agent))
                {
                    $bname = 'Netscape';
                    $ub = "Netscape";
                }

                return array(
                    'userAgent' => $u_agent,
                    'name'      => $bname,
                    'platform'  => $platform,
                );
            }
            
        function clean(&$params)
            {

		$date = JFactory::getDate();
		$date->setOffset(JFactory::getApplication()->getCfg('offset'));

                $month = date('m');
                $year = date('Y');
                $monthstart = mktime(0, 0, 0, $month, 1, $year);
                
                $query = "select count(*) from ".$this->db->nameQuote('#__cwtraffic_total');
                $this->db->setQuery($query);
                $numrows = $this->db->loadResult();

                if(!$numrows)
                {
                    $query = "INSERT INTO ".$this->db->nameQuote('#__cwtraffic_total')." VALUES(0)";
                    $this->db->setQuery($query);
                    $this->db->query();
                }

                $cleanstart = $monthstart - (8 * 24 * 60 * 60);
                $query = "SELECT count(*) FROM ".$this->db->nameQuote('#__cwtraffic')." WHERE ".$this->db->nameQuote('tm')."<".$this->db->quote($cleanstart);
                $this->db->setQuery($query);
                $oldrows = $this->db->loadResult();

                if($oldrows)
                {
                    $query = "UPDATE ".$this->db->nameQuote('#__cwtraffic_total')." SET ".$this->db->nameQuote('tcount')."=".$this->db->nameQuote('tcount')."+".$this->db->quote($oldrows);
                    $this->db->setQuery($query);
                    $this->db->query();

                    $query = "DELETE FROM ".$this->db->nameQuote('#__cwtraffic')." WHERE ".$this->db->nameQuote('tm')."<".$this->db->quote($cleanstart);
                    $this->db->setQuery($query);
                    $this->db->query();
                }

                return;
            }
}
